package com.salim.summary;

import java.util.Random;

public class MemoryModelTester {
    int x,y,x_read,y_read;

    Thread createThread1(){
        return new Thread(new Runnable(){
            @Override
            public void run(){
                randomSleep();
                x = 1;
                y_read = y;
            }
        });
    }

    private void randomSleep() {
        try {
            Thread.sleep(new Random().nextInt(30));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    Thread createThread2(){
        return new Thread(new Runnable(){
            @Override
            public void run(){
                randomSleep();
                y = 1;
                x_read = x;
            }
        });
    }

    /**
     * 出现问题的原因
     * 1.内存可见性
     *   线程1对x的赋值还没被线程2看到 本地内存、程序计数器(PC寄存器)相关
     * 2.乱序执行
     *   执行过程中顺序可能被打乱 cpu乱序执行、编译器乱序执行相关
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        while (true){
            MemoryModelTester  tester = new MemoryModelTester();
            Thread thread1 = tester.createThread1();
            Thread thread2 = tester.createThread2();

            thread1.start();
            thread2.start();

            thread1.join();
            thread2.join();

            System.out.println(String.format(
                "(%d, %d)", tester.x_read,tester.y_read
            ));

            if(tester.x_read ==0 && tester.y_read==0){
                throw new RuntimeException("0,0出现了");
            }
        }

    }
}
